package com.ym.b2b.user.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.ym.b2b.cache.configcache.WebAppConfig;
import com.ym.b2b.commons.conf.B2BConstants;
import com.ym.b2b.commons.conf.WebTokenUser;
import com.ym.b2b.commons.controller.BaseController;
import com.ym.b2b.commons.log.CusLog;
import com.ym.b2b.commons.util.AESSecurityUtil;
import com.ym.b2b.commons.util.CheckData;
import com.ym.b2b.commons.util.MailBean;
import com.ym.b2b.commons.util.MailUtil;
import com.ym.b2b.user.service.EmCUserService;
import com.ym.b2b.user.sqlbean.EmCUser;
import com.ym.b2b.user.vo.FindPwdBean;
import com.zc.commons.base.Result;
import com.zc.commons.util.ZcStringUtil;

@Controller
@RequestMapping("/user")
public class EmCUserController extends BaseController {

    @Autowired
    private EmCUserService emCUserService;

    @Resource
    private JavaMailSender mailSender;
    
    @Resource
    
    private JdbcTemplate jdbc;

    /**
     * 用户统一登录入口：
     * 
     * @Title: login
     * @Description: TODO
     * @Param @param emCuser
     * @Param @param req
     * @Param @return
     * @Return Object
     * @Throws
     */
    @RequestMapping(value = "login.s")
    public Object login(EmCUser emCuser, HttpServletRequest req) {
		long s = System.currentTimeMillis();
    	logger.info("用户: " + emCuser.getLoginName() + "开始登录时间," + s);
        ModelAndView m = new ModelAndView();
        Result ret = new Result();
        try {
            String rand1 = (String) req.getSession().getAttribute("rand");
            emCuser.setValidCodeSession(rand1);
            ret = emCUserService.login(emCuser);
            m.addObject("result", ret);
            if (ret.getCode().equals(Result.CODE_100)) {
                m.setViewName("login");
                return m;
            }
            CusLog.writeLog("客户：" + emCuser.getLoginName() + " ip:" + CheckData.getIpAddr(req) + " 登录系统.", "USER", 2);
            // 登录成功 移出原来的 session
            req.getSession().removeAttribute(B2BConstants.WEB_USER_TOKEN);
            req.getSession().removeAttribute(B2BConstants.WEB_PROVIDER_TOKEN);
            req.getSession().removeAttribute(B2BConstants.WEB_AGENT);

            if (null != ret.getData("user")) {
                req.getSession().setAttribute(B2BConstants.WEB_USER_TOKEN, ret.getData("user"));
                System.out.println("user");
            }
            if (null != ret.getData("providerUser")) {
                req.getSession().setAttribute(B2BConstants.WEB_PROVIDER_TOKEN, ret.getData("providerUser"));
                System.out.println("providerUser");
            }
            if (null != ret.getData("agent")) {
                req.getSession().setAttribute(B2BConstants.WEB_AGENT, ret.getData("agent"));
                System.out.println("agent");
            }

            // m.setViewName("redirect:" + emCuser.getLastUrl());
            if("111111".equals(emCuser.getLoginPwd())){
            	req.getSession().setAttribute(B2BConstants.SIMPLE_PASSWORD, "1");
            	m.setViewName("redirect:/views/jsp/center/c_user_password.jsp");
            }else{
            	m.setViewName("redirect:/views/jsp/center/c_user_center.jsp");
            }
            logger.info("用户: " + emCuser.getLoginName() + "花费时间: " + (System.currentTimeMillis() - s));
            return m;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, e.getMessage());
            m.addObject("result", ret);
            m.setViewName(B2BConstants.WEB_ERROR);
            return m;
        }
    }

    @RequestMapping(value = "ajaxlogin.s")
    @ResponseBody
    public Result ajaxlogin(EmCUser emCuser, HttpServletRequest req) {
        Result ret = new Result();
        try {
            ret = emCUserService.login(emCuser);

            req.getSession().setAttribute(B2BConstants.WEB_USER_TOKEN, ret.getData("user"));

        } catch (Exception e) {
            ret.setCodeResult(Result.CODE_100, e.getMessage());
        }
        return ret;
    }

    /**
     * 登录退出
     */
    @RequestMapping(value = "loginOut.s")
    public Object loginOut(HttpServletRequest req) {
        ModelAndView m = new ModelAndView();
        Object o1 = req.getSession().getAttribute(B2BConstants.WEB_USER_TOKEN);
        if (null != o1) {
            req.getSession().removeAttribute(B2BConstants.WEB_USER_TOKEN);
        }
        Object o2 = req.getSession().getAttribute(B2BConstants.WEB_PROVIDER_TOKEN);
        if (null != o2) {
            req.getSession().removeAttribute(B2BConstants.WEB_PROVIDER_TOKEN);
        }
        Object o3 = req.getSession().getAttribute(B2BConstants.MANAGER_TOKEN);
        if (null != o3) {
            req.getSession().removeAttribute(B2BConstants.MANAGER_TOKEN);
        }
        Object o4 = req.getSession().getAttribute(B2BConstants.WEB_AGENT);
        if (null != o4) {
            req.getSession().removeAttribute(B2BConstants.WEB_AGENT);
        }

        m.setViewName("login");
        return m;
    }

    @RequestMapping(value = "sendFindPwdEmail.s")
    @ResponseBody
    public Result sendFindPwdEmail(HttpServletRequest req, String loginName) {
        Result ret = new Result();
        EmCUser emCuser = new EmCUser();
        emCuser.setLoginName(loginName);
        EmCUser user = emCUserService.searchEmCUser(emCuser);
        if (user != null) {

            String email = user.getEmail();
            // check email
            if (ZcStringUtil.isBlank(email)) {
                ret.setCodeResult(Result.CODE_100, "您注册的时候没有填写邮箱!");
                return ret;
            }
            if (!CheckData.checkEmail(email)) {
                ret.setCodeResult(Result.CODE_100, "您的邮箱格式不正确!");
                return ret;
            }
            MailBean b = new MailBean();
            b.setType(2);
            b.setToAddress(email);
            b.setMailTitle("密码找回");

            // 获取对称加密串
            FindPwdBean fb = new FindPwdBean();
            fb.setLoginName(loginName);
            fb.setStartTime(CheckData.getfDate("yyyyMMddhhmmss"));

            String validDataM2 = AESSecurityUtil.encrypt(JSON.toJSONString(fb), AESSecurityUtil.KEY);
            if (ZcStringUtil.isBlank(validDataM2)) {
                ret.setCodeResult(Result.CODE_100, "发送找回邮件失败 ,请联系客服。");
                return ret;
            }

            // 获取模板
            String content = "<p>亲爱的宣城医药在线客户： 您好</p>" +

            "<p>欢迎您访问宣城医药在线，请点击以下链接完成密码找回</p>" +

            "<p>" + WebAppConfig.getConfigMap().get("WEB_URL") + "/user/forwordPwdJsp.s?validData=" + validDataM2
                             + "</p>" +

                             "<p>本邮件请使用HTML方式显示，否则以上链接可能无法正确显示</p>" +

                             "<p>如果点击以上链接不能进入，请把以上链接复制粘贴到浏览器的地址栏，然后回车来执行此链接。</p>" +

                             "<p>此链接30分钟内有效，" + "<br>";
            b.setMailContent(content);
            MailUtil uU = new MailUtil();
            ret = uU.sendMail(b);
            ret.putData("user", user);
            return ret;
        } else {
            ret.setCodeResult(Result.CODE_100, "该用户不存在,您再仔细想想!");
            return ret;
        }
    }

    @RequestMapping(value = "forwordPwdJsp.s")
    public ModelAndView forwordPwdJsp(String validData, HttpServletRequest req) {

        ModelAndView m = new ModelAndView();
        String email_not_access_url = "user/email_not_access_d";
        if (ZcStringUtil.isBlank(validData)) {
            m.setViewName(email_not_access_url);
            m.addObject("info", "参数不合法、请不要非法访问!");
            return m;
        }

        // 解析串
        String de = AESSecurityUtil.decrypt(validData, AESSecurityUtil.KEY);
        if (ZcStringUtil.isBlank(de)) {
            m.setViewName(email_not_access_url);
            m.addObject("info", "参数不合法、请不要非法访问!");
            return m;
        }
        FindPwdBean b = null;
        try {
            b = JSON.parseObject(de, FindPwdBean.class);
        } catch (Exception e) {
            e.printStackTrace();
            m.setViewName(email_not_access_url);
            m.addObject("info", "参数不合法、请不要非法访问!");
            return m;
        }
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");// 设置日期格式
            if (CheckData.toDateFromFormate(df.format(get30MinitesAgo()), "yyyyMMddhhmmss").after(CheckData.toDateFromFormate(b.getStartTime(),
                                                                                                                              "yyyyMMddhhmmss"))) {
                m.setViewName(email_not_access_url);
                m.addObject("info", "连接已经超时,请尝试重新申请!");
                return m;
            }
        } catch (Exception e) {
            e.printStackTrace();
            m.setViewName(email_not_access_url);
            m.addObject("info", "连接已经失效,请尝试重新申请!");
            return m;
        }
        m.addObject("loginName", b.getLoginName());
        m.setViewName("user/reset_pwd_d");
        return m;
    }

    private Date get30MinitesAgo() throws Exception {
        Date rtn = null;
        GregorianCalendar cal = new GregorianCalendar();
        Date date = new Date();
        cal.setTime(date);
        cal.add(12, -30);
        rtn = cal.getTime();

        return rtn;
    }

    /**
     * 获取用户信息
     */
    @ResponseBody
    @RequestMapping(value = "showUserInformation.s")
    public Result showUserInformation(EmCUser emCuser, HttpServletRequest req) {
        Result ret = new Result();
        try {
            WebTokenUser wtu = getWebTokenUser(req);
            if (null == wtu) {
                ret.setCodeResult(Result.CODE_100, "请先登录");
                return ret;
            }
            emCuser.setUserId(Long.parseLong(String.valueOf(wtu.getUserId())));
            EmCUser user = emCUserService.searchEmCUser(emCuser);
            ret.putData("user", user);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     * @Title: updateUserInformation
     * @Description: 修改
     */
    @ResponseBody
    @RequestMapping(value = "updateUserInformation.s")
    public Result updateUserInformation(EmCUser emCuser, HttpServletRequest req) {
        Result ret = new Result();
        try {
            Date dt = new Date();
            emCuser.setUpdateDate(dt);
            WebTokenUser wtu = getWebTokenUser(req);
            emCuser.setUserId(Long.parseLong(String.valueOf(wtu.getUserId())));
            ret = emCUserService.update(emCuser);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     * @Title:
     * @Description: 修改密码
     */
    @ResponseBody
    @RequestMapping(value = "updateUserPassword.s")
    public Result updateUserPassword(EmCUser emCuser, HttpServletRequest req) {
        Result ret = new Result();
        try {
            WebTokenUser wtu = getWebTokenUser(req);
            if (null == wtu) {
                ret.setCodeResult(Result.CODE_100, "没有登录!");
                return ret;
            }
            emCuser.setUserId(wtu.getUserId());
            ret = emCUserService.updateUserPassword(emCuser);
        } catch (Exception e) {
            e.printStackTrace();
            ret.setCodeResult(Result.CODE_100, e.getMessage());
        }
        return ret;
    }

    @RequestMapping(value = "findUserPassword.s")
    public ModelAndView findUserPassword(EmCUser emCuser, HttpServletRequest req) {
        ModelAndView m = new ModelAndView();
        try {
            Result ret = emCUserService.findUserPassword(emCuser);
            m.addObject("ret", ret);
            m.setViewName("user/find_pwd_result_d");
        } catch (Exception e) {
            e.printStackTrace();
            m.setViewName(B2BConstants.WEB_ERROR);
        }

        return m;
    }
    
    @ResponseBody
    @RequestMapping(value = "signContract.s")
    public Result signContract(EmCUser emCuser, HttpServletRequest req) {
        Result ret = new Result();
        try {
            WebTokenUser wtu = getWebTokenUser(req);
            if (null == wtu) {
                ret.setCodeResult(Result.CODE_100, "没有登录!");
                return ret;
            }
         // 查询合同是否签订
            int isCompact = jdbc.queryForInt("select count(*) from EM_C_BUYER_ELECTRON_COMPACT where buyer_code='"
                                             + wtu.getBuyerCode() + "' and compact_type=1");
            if(isCompact>0){
            	ret.setCodeResult(Result.CODE_100, "已经签订过了 无需再次签订!");
            	return ret;
            }
            jdbc.execute("insert into EM_C_BUYER_ELECTRON_COMPACT(compact_id,buyer_code,compact_text,compact_type)values(seq_ELECTRON_COMPACT.nextval,'"+wtu.getBuyerCode()+"','零时内容',1)");
            
            wtu.setIsCompact("1");
        } catch (Exception e) {
            e.printStackTrace();
            ret.setCodeResult(Result.CODE_100, "系统异常");
        }
        return ret;
    }
    @ResponseBody
    @RequestMapping(value = "checkPayCompact.s")
    public Result checkPayCompact(EmCUser emCuser, HttpServletRequest req) {
        Result ret = new Result();
        try {
            WebTokenUser wtu = getWebTokenUser(req);
            if (null == wtu) {
                ret.setCodeResult(Result.CODE_100, "没有登录!");
                return ret;
            }
         // 查询合同是否签订
            int isCompact = jdbc.queryForInt("select count(*) from EM_C_BUYER_ELECTRON_COMPACT where buyer_code='"
                                             + wtu.getBuyerCode() + "' and compact_type=2");
            
            
            if(isCompact<1){
            	ret.setCodeResult(Result.CODE_100, "尚未签订合同!");
            	return ret;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ret.setCodeResult(Result.CODE_100,"系统异常" );
        }
        return ret;
    }
    @ResponseBody
    @RequestMapping(value = "signPayCompact.s")
    public Result signPayCompact(EmCUser emCuser, HttpServletRequest req) {
    	 Result ret = new Result();
         try {
             WebTokenUser wtu = getWebTokenUser(req);
             if (null == wtu) {
                 ret.setCodeResult(Result.CODE_100, "没有登录!");
                 return ret;
             }
          // 查询合同是否签订
             int isCompact = jdbc.queryForInt("select count(*) from EM_C_BUYER_ELECTRON_COMPACT where buyer_code='"
                                              + wtu.getBuyerCode() + "' and compact_type=2");
             if(isCompact>0){
             	ret.setCodeResult(Result.CODE_100, "已经签订过了 无需再次签订!");
             	return ret;
             }
             jdbc.execute("insert into EM_C_BUYER_ELECTRON_COMPACT(compact_id,buyer_code,compact_text,compact_type)values(seq_ELECTRON_COMPACT.nextval,'"+wtu.getBuyerCode()+"','零时内容',2)");
             
         } catch (Exception e) {
             e.printStackTrace();
             ret.setCodeResult(Result.CODE_100,"系统异常" );
         }
         return ret;
    }
    

}
